//
//  XHOAViewController.swift
//  gu-新浪微博
//
//  Created by xiaohui on 16/6/26.
//  Copyright © 2016年 gusheghui. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class XHOAViewController: UIViewController {

    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    override func loadView() {
        view = webView
    }
    
    private func setupUI(){
//        view.backgroundColor = UIColor.whiteColor()
        setupNav()
    }
    
    
    private func setupNav(){
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "btnClick")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "fillBtnClick")
        navigationItem.title = "OAuth登陆"
    }
 
    @objc private func btnClick(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func fillBtnClick(){
              
//let jsString = "document.getElementById('userId').value='muqi70595723@163.com',document.getElementById('passwd').value='bbb333'"
        
        let jsString = "document.getElementById('userId').value='13001997970',document.getElementById('passwd').value='xiaohui'"
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    //懒加载创建webView
    private lazy var webView:UIWebView = {
        
        let webView = UIWebView()
        webView.delegate = self
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(REDIRECT_URI)")
        
        let requst = NSURLRequest(URL: url!)
        webView.loadRequest(requst)
        
        
        return webView
    }()
}

extension XHOAViewController :UIWebViewDelegate{
    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    //加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //url转换成字符串
        let urlString = request.URL?.absoluteString
        
        //query 是指问号后面的部分
//        http://www.baidu.com/?code=09cca3a1883d181b1741135574f280a2
        
        if let u = urlString where u.hasPrefix(REDIRECT_URI){
            let query = request.URL?.query
            if let q = query {
                let code = q.substringFromIndex("code=".endIndex)

                loadUserAccount(code)
                
                
                //拿到code没有必要继续加载！！！！
                return false
            }
        }
        return true
    }
}

//回调授权https://api.weibo.com/oauth2/access_token

extension XHOAViewController{
    func loadUserAccount(code:String){
        
        XHNetworkTools.sharedTools.loadUserAcount(code, success: { (response) -> () in
//            print(response)
            guard let res = response as? [String :AnyObject] else{
                
                return
            }//字典转模型
            let userAccount = XHUserAccount(dict: res)
            
            print("成功:\(userAccount)")
            self.loadUserInfo(userAccount)
            }) { (error) -> () in
                print(error)
                SVProgressHUD.showErrorWithStatus("请求错误")
        }
    }
    
    func loadUserInfo(userAccount:XHUserAccount){
        XHNetworkTools.sharedTools.authLoadUserInfo(userAccount, success: { (response) -> () in
            guard let res = response as? [String:AnyObject]
                else{
                    return
            }
            userAccount.avatar_large = res["avatar_large"]as?String
            userAccount.screen_name = res["screen_name"]as?String
            //通过归档解档保存 个人信息
            
            XHUserAccountTools.sharedTools.saveUserAccount(userAccount)
            
            
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                SVProgressHUD.dismiss()
                //拿到数据以后 通知appDelegate 切换控制器
                NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVcNoti, object: nil)
            })
            
            
            
            
            }) { (error) -> () in
                
        }
    }
    
}




